<template>
  <div class="headerBox">
    <NuxtLogo />

    <div class="hadnderNav">
      <nuxt-link to="/"><span>首页</span></nuxt-link>
      <nuxt-link to="/news/hot"><span>新闻</span></nuxt-link>
      <nuxt-link to="/about"><span>关于</span></nuxt-link>
      <nuxt-link to="/classify/live?page=1"><span>生活指南</span></nuxt-link>
      <nuxt-link to="/classify/recreation"><span>娱乐</span></nuxt-link>

    </div>
    <div class="user_name">
      <a-dropdown v-show="token">
        <span>{{ userInfo.nickname }}</span>
        <a-menu slot="overlay">
          <a-menu-item>
            <a href="javascript:;" @click="logout">退出登陆</a>
          </a-menu-item>
        </a-menu>
      </a-dropdown>

      <span v-show="!token" style="cursor: pointer;" @click="login">未登陆</span>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex"
import Cookies from 'js-cookie'
export default {
  name: "HeaderBox",
  computed: {
    ...mapState("user", ["userInfo", "token"])
  },
  mounted() {
    console.log("headerBox 组件", this.userInfo, this.token);
  },
  methods: {
    // 登陆
    async login() {

      const { code, data } = await this.$api.login()

      if (code === 200) {
        // 将 token 添加到 cookie 中
        Cookies.set("token", data.token)
        // 将 token 添加到 vuex 中
        this.$store.commit("user/SET_TOKEN", data.token)
        this.$router.push("/")
        setTimeout(() => {
          location.reload()
        }, 1000)
      }
    },
    // 退出登陆
    logout() {
      // 移除 cookies
      Cookies.remove("userInfo")
      Cookies.remove("token")

      // 清空 vuex 中的数据
      this.$store.commit("user/SET_USERINFO", {})
      this.$store.commit("user/SET_TOKEN", "")
    }
  }

}
</script>

<style lang="scss" scoped>
.headerBox {
  height: 40px;
  display: flex;
  align-items: center;
  position: relative;


  .user_name {
    position: absolute;
    right: 8px;
    top: 10px;
  }
}

.hadnderNav {
  display: flex;
  margin-left: 20px;

  span {
    padding: 0 6px;
  }
}
</style>
